Import cal3d

Class CalPlane

	Field a:Float,b:Float,c:Float,d:Float
	
	Method New()
	
		a = 0
		b = 0
		c = 0
		d = 0
	
	End


	Method eval:Float(p:CalVector)
	
		Return p.x * a + p.y * b + p.z * c + d
	
	End
	
	Method setPosition:Void(p:CalVector)
	
		d = -p.x * a - p.y * b - p.z * c
	
	End
	
	Method setNormal:Void(n:CalVector)
	
		 a = n.x
		 b = n.y
		 c = n.z
		 d = -1e32	
			
	End
	

	Method dist:Float(p:CalVector)
	
		return Abs( (p.x * a + p.y * b + p.z * c + d) / Sqrt(a * a + b * b + c * c) )
	
	End

End Class



Class CalBoundingBox

	Field plane:CalPlane[]
	
	Method New()
		plane = New CalPlane[6]
		For Local i:Int = 0 To 5
		
			plane[i] = New CalPlane
		
		Next
	
	End
	
	Method computePoints:CalVector[](point:CalVector[])
	
		If points = Null Or points.Length < 8 Then
			points = New CalVector[8]
		Endif
		Local m:CalMatrix = New CalMatrix
	
		'local plane = plane	 
		Local p:int = 0
		For Local i:Int=0 To 1
			For Local j:Int = 2 To 3
				For Local k:Int = 4 To 5
					Local x:Float,y:Float,z:Float
	
					m.dxdx = plane[i].a m.dxdy = plane[i].b m.dxdz = plane[i].c        
					m.dydx = plane[j].a m.dydy = plane[j].b m.dydz = plane[j].c        
					m.dzdx = plane[k].a m.dzdy = plane[k].b m.dzdz = plane[k].c
	
					Local det:float = m.det()
				   
					If det <> 0  Then
						m.dxdx = -plane[i].d 
						m.dxdy = plane[i].b 
						m.dxdz = plane[i].c        
						m.dydx = -plane[j].d 
						m.dydy = plane[j].b 
						m.dydz = plane[j].c        
						m.dzdx = -plane[k].d 
						m.dzdy = plane[k].b 
						m.dzdz = plane[k].c
	
						x = m.det() / det
	
						m.dxdx = plane[i].a 
						m.dxdy = -plane[i].d 
						m.dxdz = plane[i].c        
						m.dydx = plane[j].a 
						m.dydy = -plane[j].d 
						m.dydz = plane[j].c        
						m.dzdx = plane[k].a 
						m.dzdy = -plane[k].d 
						m.dzdz = plane[k].c
	
						y = m.det() / det
	
						m.dxdx = plane[i].a 
						m.dxdy = plane[i].b 
						m.dxdz = -plane[i].d        
						m.dydx = plane[j].a 
						m.dydy = plane[j].b 
						m.dydz = -plane[j].d        
						m.dzdx = plane[k].a
						m.dzdy = plane[k].b 
						m.dzdz = -plane[k].d
	
						z = m.det() / det
	
						If points[p] <> Null Then
							points[p].assign(x, y, z)
						Else
							points[p] = New CalVector(x, y, z)
						Endif
					Else 
						If points[p] Then
							points[p].assign(0, 0, 0)
						Else
							points[p] = New CalVector(0, 0, 0)
						Endif
					Endif
	
					p=p+1
				Next
			Next
		Next
	
		return points	
	
	End
	
	

End Class
